import socket

# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名和端口号
host = '127.0.0.1'
port = 9000

# 绑定端口号
server_socket.bind((host, port))

# 设置监听队列，指定最多可以连接多少个客户端
server_socket.listen(5)

while True:
    # 建立客户端连接
    client_socket, addr = server_socket.accept()
    print('连接地址：', addr)

    # 向客户端发送消息
    msg = '欢迎访问服务器！' + "\r\n"
    client_socket.send(msg.encode())

    try:
        # 接收客户端消息
        with client_socket:
            print('消息来自：', addr)
            while True:
                data = client_socket.recv(1024)
                # 判断信息长度(超过1000则断开连接，防止客户端占满服务器接收缓存空间)
                if data and len(data) <= 1000:
                    message = data.decode()
                    print('收到客户端消息：', message)
                    # 发送响应消息给客户端
                    response = '服务器收到消息：{}'.format(message)
                    client_socket.sendall(response.encode())
                else:
                    print(f'{addr}已断开连接')
                    break

    finally:
        # 关闭客户端Socket连接
        client_socket.close()

# 关闭服务器Socket连接
server_socket.close()
